package
{
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.external.ExternalInterface;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.system.System;
	import flash.utils.ByteArray;
	import flash.utils.setTimeout;
	
	import util.JPGEncoderIMP;
	import util.LoadUtil;
	import util.PNGEncoder;
	
	import view.CutArea;
	import view.MessagePanel;
	import view.PrviewArea;
	import view.View;
	import view.event.LocalDataReadyEvent;

	public class MainController
	{
		private var _view:View;
		private var _cutArea:CutArea;
		private var _prview:PrviewArea;
		private var _loadUtil:LoadUtil;
		public function MainController(view:View):void
		{
			_view=view;
			_cutArea=_view.cutArea;
			_prview=_view.prview;
			_loadUtil=new LoadUtil;
			
			_view.uploadBtn.addEventListener(MouseEvent.CLICK,onUpload);
			_view.saveBtn.addEventListener(MouseEvent.CLICK,onSave);
			_view.cancelBtn.addEventListener(MouseEvent.CLICK,onCancel);
			_view.cutArea.addEventListener(Event.CHANGE,onChangeCut);
			_loadUtil.addEventListener(LocalDataReadyEvent.READY,onReady);
		}
		private function onReady(e:LocalDataReadyEvent):void
		{
			_cutArea.load(e.data);
		}
		private function onChangeCut(e:Event):void
		{
			_prview.load(_cutArea.loader,_cutArea.selectedRectangle);
		}
		private function onUpload(e:Event):void
		{
			_loadUtil.load();
		}
		private function onSave(e:Event):void
		{
			var bd:BitmapData=_prview.data;
			if(!bd)
			{
				MessagePanel.getInstance().showLoading("请先截取合适的区域",false,2);
				return;
			}
			
			if(!_loading)
			{
				_loading=true;
				MessagePanel.getInstance().showLoading("图片正在处理中,请稍等...",true,0);
//				JPGEncoder();
//				return;
				setTimeout(callLater,500);
			}
		}
		private function callLater():void
		{
				var req:URLRequest = new URLRequest(CutPhotoConfig.serverUrl);
				req.data = PNGEncoder.encode(_prview.data);
				req.method = URLRequestMethod.POST;
				req.contentType = "application/octet-stream";
				var loader:URLLoader = new URLLoader();
				loader.dataFormat = URLLoaderDataFormat.BINARY;
				configureListeners(loader);
				loader.load(req);
				MessagePanel.getInstance().showLoading("图片正在上传中,请稍等...",true,0);
		}

		private var _loading:Boolean=false;
		private function onProgress(e:ProgressEvent):void
		{
		}
		private function onIOError(e:Event):void
		{
			removeListeners(e.currentTarget as IEventDispatcher);
			MessagePanel.getInstance().showLoading("上传失败!");
			_loading=false;
		}
		private function onUploadComplete(e:Event):void
		{
			removeListeners(e.currentTarget as IEventDispatcher);
			MessagePanel.getInstance().showLoading("上传成功!");
			_loading=false;
			var by:ByteArray=e.target.data as ByteArray;
			ExternalInterface.call("FlashResult",by.readUTFBytes(by.length));
		}
		private function openHandler(event:Event):void {
			trace("openHandler: " + event);
		}
		
		private function securityErrorHandler(event:SecurityErrorEvent):void {
			trace("securityErrorHandler: " + event);
			_loading=false;
		}
		
		private function httpStatusHandler(event:HTTPStatusEvent):void {
			trace("httpStatusHandler: " + event);
		}
		private function configureListeners(dispatcher:IEventDispatcher):void {
			dispatcher.addEventListener(Event.COMPLETE, onUploadComplete);
			dispatcher.addEventListener(Event.OPEN, openHandler);
			dispatcher.addEventListener(ProgressEvent.PROGRESS, onProgress);
			dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			dispatcher.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
			dispatcher.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
		}
		private function removeListeners(dispatcher:IEventDispatcher):void {
			dispatcher.removeEventListener(Event.COMPLETE, onUploadComplete);
			dispatcher.removeEventListener(Event.OPEN, openHandler);
			dispatcher.removeEventListener(ProgressEvent.PROGRESS, onProgress);
			dispatcher.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			dispatcher.removeEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
			dispatcher.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
		}
		private  var jpgencoder:JPGEncoderIMP; 
		 private function JPGEncoder():void
		{
			 if(jpgencoder)
			 {
				 jpgencoder.removeEventListener(ProgressEvent.PROGRESS,encoderProgress);
				 jpgencoder.removeEventListener(Event.COMPLETE,encoderComplete);
			 }
			 jpgencoder=new JPGEncoderIMP(50);
			 jpgencoder.addEventListener(ProgressEvent.PROGRESS,encoderProgress);
			 jpgencoder.addEventListener(Event.COMPLETE,encoderComplete);
			 jpgencoder.encodeAsync(_prview.data);
		}
		 private function encoderProgress(e:ProgressEvent):void
		 {
			 if(e.bytesLoaded/e.bytesTotal<1){
				 MessagePanel.getInstance().showLoading("图像转换中 "+Math.floor((e.bytesLoaded/e.bytesTotal)*100)+"%",true,0);
			 }
		 }
		 private var loader:URLLoader; 
		 private function encoderComplete(e:Event):void
		 {
			 var jpg:JPGEncoderIMP=(e.target as JPGEncoderIMP);
			 jpg.removeEventListener(ProgressEvent.PROGRESS,encoderProgress);
			 jpg.removeEventListener(Event.COMPLETE,encoderComplete);
			 
			 var req:URLRequest = new URLRequest(CutPhotoConfig.serverUrl);
			 req.data =jpg.ba;
			 req.method = URLRequestMethod.POST;
			 req.contentType = "application/octet-stream";
			 if(loader)
			 {
				 removeListeners(loader as IEventDispatcher);
			 }
			 loader = new URLLoader();
			 loader.dataFormat = URLLoaderDataFormat.BINARY;
			 configureListeners(loader);
			 loader.load(req);
			 MessagePanel.getInstance().showLoading("图片正在上传中,请稍等...",true,0);
			 jpgencoder.dispose();
		 }
		private function onCancel(e:Event):void
		{
			ExternalInterface.call("FlashResult","remove");
			return;
			if(jpgencoder)
			{
				jpgencoder.removeEventListener(ProgressEvent.PROGRESS,encoderProgress);
				jpgencoder.removeEventListener(Event.COMPLETE,encoderComplete);
				jpgencoder.dispose();
			}
			if(loader)
			{
				removeListeners(loader as IEventDispatcher);
				try
				{
					loader.close();
				} 
				catch(error:Error) 
				{
				}
			}
			MessagePanel.getInstance().hideLoading();
			_loading=false;
		}
		//		private function encoderProgress(e:ProgressEvent):void
		//		{
		//			if(e.bytesLoaded/e.bytesTotal<1){
		//				MessagePanel.getInstance().setText("图像转换中");
		//			}
		//		}
		//		private function encoderComplete(e:Event):void
		//		{
		//			var jpg:JPGEncoderIMP=(e.target as JPGEncoderIMP);
		//			jpg.removeEventListener(ProgressEvent.PROGRESS,encoderProgress);
		//			jpg.removeEventListener(Event.COMPLETE,encoderComplete);
		//			MessagePanel.getInstance().setText("图像转换完成");
		//		//	trace(jpg.ba);
		//			var f:FileReference=new FileReference;
		//			f.save(jpg.ba,"temp.jpg");
		//		}
		//			var jpgencoder:JPGEncoderIMP=new JPGEncoderIMP(100);
		//			jpgencoder.addEventListener(ProgressEvent.PROGRESS,encoderProgress);
		//			jpgencoder.addEventListener(Event.COMPLETE,encoderComplete);
		//			jpgencoder.encodeAsync(bd)
		//					var f:FileReference=new FileReference;
		//					f.save(PNGEncoder.encode(bd),"temp.png");
	}
}